package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.FocusUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.FocusUser;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private FocusUserApi focusUserApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 上传视频
     *
     * @param videoThumbnail 封面图片文件
     * @param videoFile      视频文件
     */
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {

        if (videoFile.isEmpty() || videoThumbnail.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }

        //1、将视频上传到FastDFS,获取访问URL
        String filename = videoFile.getOriginalFilename();  // abc.mp4
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //2、将封面图片上传到阿里云OSS，获取访问的URL
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //3、构建Videos对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火");
        //4、调用API保存数据
        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)) {
            throw new BusinessException(ErrorResult.error());
        }

        //发送消息
        mqMessageService.sendLogMessage(UserHolder.getUserId(), "0301", "video", videoId);
    }

    //查询视频列表
    @Cacheable(
            value = "videos",
            key = "T(com.tanhua.server.interceptor.UserHolder).getUserId()+'_'+#page+'_'+#pagesize")
    //userid _ page_pagesize
    public PageResult queryVideoList(Integer page, Integer pagesize) {
        Long userId = UserHolder.getUserId();
        //1、查询redis数据
        String redisKey = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String redisValue = redisTemplate.opsForValue().get(redisKey);
        redisValue = null;
        //2、判断redis数据是否存在，判断redis中数据是否满足本次分页条数
        List<Video> list = new ArrayList<>();
        int redisPages = 0;
        if (!StringUtils.isEmpty(redisValue)) {
            //3、如果redis数据存在，根据VID查询数据
            String[] values = redisValue.split(",");
            //判断当前页的起始条数是否小于数组总数
            if ((page - 1) * pagesize < values.length) {
                List<Long> vids = Arrays.stream(values).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e -> Long.valueOf(e))
                        .collect(Collectors.toList());
                //5、调用API根据PID数组查询动态数据
                list = videoApi.findMovementsByVids(vids);
            }
            redisPages = PageUtil.totalPage(values.length, pagesize);
        }
        //4、如果redis数据不存在，分页查询视频数据
        if (list.isEmpty()) {
            //page的计算规则，  传入的页码  -- redis查询的总页数
            list = videoApi.queryVideoList(page - redisPages, pagesize);  //page=1 ?
        }
        //5、提取视频列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //6、查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //7、构建返回值
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo info = map.get(video.getUserId());
            if (info != null) {
                VideoVo vo = VideoVo.init(info, video);
                //从redis中查询用户点赞信息
                String like = (String) redisTemplate.opsForHash().get("VIDEO_LIKE_", info.getId().toString() + video.getId().toString());
                vo.setHasLiked(like == null ? 0 : 1);
                //从redis中查询用户关注详情
                String focus = (String) redisTemplate.opsForHash().get("VIDEO_FOCUS_", vo.getUserId().toString() + userId.toString());
                vo.setHasFocus(focus == null ? 0 : 1);
                vos.add(vo);
            }
        }

        return new PageResult(page, pagesize, 0l, vos);
    }

    /**
     * 用户给小视频点赞
     *
     * @param id
     */
    public void addLike(String id) {
        //获取当前点赞用户id
        Long userId = UserHolder.getUserId();
        //按当前视频id更新点赞数据
        videoApi.updateLikeCount(id, CommentType.LIKE);
        //将点赞信息保存到redis中
        redisTemplate.opsForHash().put("VIDEO_LIKE_", userId.toString() + id, "1");
    }

    public void videoDisLike(String id) {
        //获取当前取消点赞用户id
        Long userId = UserHolder.getUserId();
        //按当前视频id更新点赞数据
        videoApi.updateDisCount(id, CommentType.LIKE);
        //将点赞信息从redis中删除
        redisTemplate.opsForHash().delete("VIDEO_LIKE_", userId.toString());
    }

    public void videoAddComments(String id, Map map) {
        //获取当前评论人的id
        Long userId = UserHolder.getUserId();
        //获取当前评论内容
        String comment = (String) map.get("comment");
        //更新评论数据
        videoApi.updateLikeCount(id, CommentType.COMMENT);
        //将评论数据添加
        commentApi.saveVideoComment(userId, id, comment);
//        //将评论数据表识道到redis中
//        redisTemplate.opsForHash().put("VIDEO_COMMENT_",userId.toString(),"1");
    }

    /**
     * 小视频评论列表
     *
     * @param page
     * @param pageSize
     * @param id
     * @return
     */
    public PageResult findVideoComments(Integer page, Integer pageSize, String id) {
        List<CommentVo> commentVoList = new ArrayList<>();
        List<Comment> comments = commentApi.findComments(id, CommentType.COMMENT, page, pageSize);
        List<Long> collect = comments.stream().map(Comment::getUserId).collect(Collectors.toList());
        if (CollUtil.isEmpty(collect)) {
            return new PageResult(page, pageSize, 0l, commentVoList);
        }
        Map<Long, UserInfo> infoMap = userInfoApi.findByIds(collect, null);
        commentVoList = comments.stream()
                .map(item -> {
                    UserInfo userInfo = infoMap.get(item.getUserId());
                    CommentVo commentVo = CommentVo.init(userInfo, item);
                    String like = (String) redisTemplate.opsForHash()
                            .get("VIDEO_COMMENTS_LIKE_", item.getId().toString() + userInfo.getId().toString());
                    commentVo.setHasLiked(like == null ? 0 : 1);
                    return commentVo;
                })
                .collect(Collectors.toList());
        return new PageResult(page, pageSize, 0l, commentVoList);
    }

    public void userFocus(Long uid) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        if (uid.toString() != null && uid.toString().equals(userId.toString())) {
            throw new BusinessException(ErrorResult.error());
        }
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(userId);
        focusUser.setVideoUserId(uid);
        focusUser.setCreated(System.currentTimeMillis());
        focusUserApi.save(focusUser);
        //将关注表示存入redis中
        redisTemplate.opsForHash().put("VIDEO_FOCUS_", uid.toString() + userId.toString(), "1");
    }

    public void userUnFocus(Long uid) {
        focusUserApi.remove(uid, UserHolder.getUserId());
        redisTemplate.opsForHash().delete("VIDEO_FOCUS_", uid.toString() + UserHolder.getUserId().toString());
    }

    public void commentsLike(String id) {

        commentApi.commentsLike(id);
        //添加标识到redis中
        redisTemplate.opsForHash().put("VIDEO_COMMENTS_LIKE_", id + UserHolder.getUserId().toString(), "1");
    }

    /**
     * 工厂方法模式是简单工厂的进一步抽象和推广，由于工厂方法模式具有多态性，
     * 工厂模式方法既保持了简单工厂的优点，同时又克服了它的缺点，简单工厂模式中的工厂类负责创建实例，
     * 那么如果有新的机型添加，就要修改工厂类，这样也不利于进一步松耦合。
     * 工厂方法模式中核心工厂类不负责所有实例的创建，而是将具体的创建工作交给了子类去完成，
     * 这个核心类成为了一个抽象工厂角色。
     * @param id
     */
    public void commentsDisLike(String id) {

        commentApi.commentsdisLike(id);
        redisTemplate.opsForHash().delete("VIDEO_COMMENTS_LIKE_", id + UserHolder.getUserId().toString());
    }
}
